package com.wnn.demo.advice;

import com.wnn.demo.pojo.Result;
import com.wnn.demo.pojo.ResultCode;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice
public class MyExceptionHandler {


    //  全局自动捕获运行异常处理
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handleException(Exception e) {
        e.printStackTrace();
        System.out.println("全局异常捕获");
        if (e.getCause() instanceof MyException){
            MyException my = (MyException) e.getCause();
            ResultCode resultCode = my.getResultCode();
            return new Result(false,resultCode.getCode(),my.getMsg());
        }
        if (e  instanceof IncorrectCredentialsException){
            return new Result(false,400,"密码错误");
        }
        if (e  instanceof UnauthorizedException){
            return new Result(false,500,"权限不足！");
        }
        return new Result(ResultCode.FALSE,"执行异常！");

    }


    //    抛出自定义异常处理
    @ExceptionHandler(MyException.class)
    @ResponseBody
    public Result handleMyException(MyException myException) {
        myException.printStackTrace();
        ResultCode resultCode = myException.getResultCode();
        String msg = myException.getMsg();
        System.out.println("自定义异常信息："+msg);
        return  new Result(false,resultCode.getCode(),msg);
    }



}